Static
When a member is declared static, it can be accessed before any objects of its class are created and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is Main( ), which is declared static because it must be called by the operating system when your program begins.

  1. static is a keyword
  2. static keyword can be used with variables ,methods, constructors and classes
  3. Static variables create common memory for all the objects.
  4. Static variables will be created while class is loading into memory; hence these are also called as class variables.
  5. Static variables will be created only once, there after it is sharable.
  6. Static constructor will be executed only once.
  7. Static constructors access only static variable; it cannot access instance variables.

 

Program on Static Variables
using System;
class abc
{
public static int a, b;
public void put()
{
Console.WriteLine("Sum of 2 nos" + (a + b));
}
}

 

class sampple
{
public static void Main(String[] args)
{
abc.a = 20;
abc.b = 30;
abc x = new abc();
x.put();
}
}

Program on static member functions
using System;
class abc
{
public static int a, b;
public static void get(int x, int y)
{
a = x;
b = y;

    }

    public static void put()
{
Console.WriteLine("Sum of 2 nos" + (a + b));
}
}

class sampple
{
public static void Main(String[] args)
{
abc.get(3, 2);
abc.put();
}
}

Static Constructors

  1. static constructors must be parameter less
  2. static constructors should not contain any access specifier.
  3. Static constructors access only static data.

Program on static constructors

using System;
class abc
{
public static int a;

    static abc()
{
a = 5;

    }

    public static void put()
{
int f=1;
for (int i = 1; i <= a; i++)
f = f * i;
Console.WriteLine("factorail" + f);
}
}

class sampple
{
public static void Main(String[] args)
{
abc x = new abc();
abc.put();
}
}